﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ruoxian_novel
{
    class Email
    {
        public static void SendTo(string mailAddress, string subject, string body)
        {
            //mailAddress 所要发送的邮箱地址，subject 邮件标题，body邮件内容
            //实例化一个发送邮件类
            MailMessage mailMessage = new MailMessage();
            //发件人邮箱地址 mailMessage.From = new MailAddress(电子邮件地址, 名称, 编码);
            mailMessage.From = new MailAddress("LeisureLoong@163.com", "若闲未来");
            //收件人邮箱地址
            mailMessage.To.Add(new MailAddress(mailAddress));
            //邮件标题
            mailMessage.Subject = subject;
            //邮件内容
            mailMessage.Body = body;
            //实例化一个SmtpClient类
            SmtpClient client = new SmtpClient();
            //使用163邮箱
            client.Host = "smtp.163.com";
            //使用安全加密连接
            client.EnableSsl = true;
            //不和请求一块发送
            client.UseDefaultCredentials = false;
            //验证发件人身份(发件人的邮箱，授权码)
            client.Credentials = new NetworkCredential("LeisureLoong@163.com", "KGBSBSRXCLHSMKKJ");
            try
            {
                //发送
                client.Send(mailMessage);
            }
            catch
            {
                MessageBox.Show("发送失败，请检查网络!");
            }
        }
        public static string RandomNumbersAndLetters(int length)
        {
            //生成length位随机数字与字母
            Random random = new Random();
            string NumbersAndLetters = "";
            for (int i = 0; i < length; i++)
            {
                if (random.Next(3) == 1)
                {
                    NumbersAndLetters += (char)('a' + random.Next(26));
                }
                else if (random.Next(3) == 2)
                {
                    NumbersAndLetters += (char)('A' + random.Next(26));
                }
                else
                {
                    NumbersAndLetters += (char)('0' + random.Next(10));
                }
            }
            return NumbersAndLetters;
        }
        public static string email(string mailAddress/*收件人*/)
        {
            //主题
            string subject = "若闲小说验证码";
            //调用数字和字母随机函数
            string Yanzhengma = RandomNumbersAndLetters(6);
            //邮件内容
            string body = "【若闲未来】你的验证码是：" + Yanzhengma + "（请注意大小写哦！）";
            //调用邮件发送
            SendTo(mailAddress, subject, body);
            //返回验证码
            return Yanzhengma;
        }
    }
}
